import os
import threading
import time
from datetime import datetime

import pystray
from PIL import Image

from notify.notification_manager import NotificationConfig
from notify.notification_sender import NotificationSender


class NotificationSystem:
    """任务提醒系统 - 使用系统托盘气泡通知"""

    def __init__(self, root, db, tray_icon=None):
        self.root = root
        self.db = db
        self.running = True
        self.reminder_sent = {
            "morning": False,  # 标记上午是否已发送提醒
            "afternoon": False,  # 标记下午是否已发送提醒
        }

        # 创建通知配置
        self.config = NotificationConfig()

        # 创建托盘图标
        self.tray_icon = tray_icon

        # 创建通知发送器
        self.notification_sender = NotificationSender(self.config, self.tray_icon, root)

        # 启动监控线程
        self.thread = threading.Thread(target=self.run)
        self.thread.daemon = True
        self.thread.start()

        # 启动系统托盘图标
        threading.Thread(target=self.tray_icon.run, daemon=True).start()

    def run(self):
        """运行提醒系统"""
        while self.running:
            now = datetime.now()
            current_time = now.time()

            # 上午上班时间检查 (9:15-9:20)
            if (now.hour == 9 and 15 <= now.minute <= 20) and not self.reminder_sent[
                "morning"
            ]:
                self.check_reminders()
                self.reminder_sent["morning"] = True

            # 下午上班时间检查 (15:15-15:20)
            elif (now.hour == 15 and 15 <= now.minute <= 20) and not self.reminder_sent[
                "afternoon"
            ]:
                self.check_reminders()
                self.reminder_sent["afternoon"] = True

            # 每天零点重置提醒状态
            elif now.hour == 0 and now.minute == 0:
                self.reminder_sent = {"morning": False, "afternoon": False}

            time.sleep(10)  # 每分钟检查一次

    def check_reminders(self):
        """检查需要提醒的任务"""
        tasks = self.db.get_today_reminders()
        for task in tasks:
            self.show_notification(task)

    def show_notification(self, task):
        """显示通知"""
        # 计算剩余天数
        days_left = (task.due_date - datetime.now().date()).days

        title = f"任务提醒: {task.title}"
        message = (
            f"截止日期: {task.due_date.strftime('%Y-%m-%d')}\n"
            f"剩余时间: {days_left}天\n"
            f"描述: {task.description}"
        )

        # 使用通知发送器发送
        self.notification_sender.send(title, message, task)

        # 标记提醒完成
        self.db.mark_reminder_done(task.id)

    def stop(self, icon=None, item=None):
        """停止提醒系统"""
        self.running = False
        self.tray_icon.stop()
        os._exit(0)  # 强制退出所有线程
